package com.ruiyi.adrobot;

import com.ruiyi.adrobot.beans.TaskDetail;
import com.ruiyi.adrobot.component.TaskExcuter;
import com.ruiyi.adrobot.mongo.robot.RobotRepository;
import com.ruiyi.adrobot.mongo.taskdetail.TaskDetailRepository;
import com.ruiyi.adrobot.utils.DateUtil;
import com.ruiyi.adrobot.utils.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableAsync
public class AdrobotApplication implements CommandLineRunner {
    @Autowired
    private TaskDetailRepository taskDetailRepository;
    @Autowired
    private RobotRepository robotRepository;
    @Autowired
    private TaskExcuter taskExcuter;

    public static void main(String[] args) {
        SpringApplication.run(AdrobotApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        // 初始化robot状态
        robotRepository.updateOnlineAndBusyFalse();
        // 初始化netty
        taskExcuter.initNetty();
        LoggerUtil.info("开启任务分配线程");
        // 开个单线程每30分钟扫描一次任务
        findTask();
        // 开启任务分发线程
        taskExcuter.excuteQueueTask();
        // 开启线程检查任务发送情况
        taskExcuter.checkSendStatus();
    }

    private void findTask() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 60秒查找一次任务
                    try {
                        TaskDetail taskDetail = taskDetailRepository.findByFinishedAndExcutedAndStartTimeLessThan(false, false, DateUtil.getCurrentTime());
                        if (null != taskDetail) {
                            taskDetailRepository.updateById(taskDetail.getId(), new Update().set("excuted", true));
                            taskExcuter.offerTask2Queue(taskDetail);
                        } else {
                            LoggerUtil.info("没有发现任务暂停30秒");
                        }
                        TimeUnit.SECONDS.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
